package org.example.test5.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {

    // 在请求处理之前进行拦截，判断用户是否登录
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 session 中的用户对象
        HttpSession session = request.getSession();
        Object user = session.getAttribute("u");

        // 如果用户未登录，重定向到登录页面
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return false;  // 阻止请求继续向下执行
        }

        // 如果已登录，允许请求继续执行
        return true;
    }

}
